<template>
	<view>
		<view style="position: relative;z-index: 9999;">
			<tui-navigation-bar :isFixed="false" :isOpacity="false" splitLine :zIndex="99999" @init="initNavigation" :scrollTop="0" title="" backgroundColor="#fff" color="#333">
				<image class="tui-header-icon" :style="{ marginTop: ((systemInfo?.statusBarHeight || 20) + 16) + 'px' }" src="https://static.wddzq.com/static/store.png"></image>
			</tui-navigation-bar>
			<view class="header-container">
				<scroll-view style="display: flex;height: 80rpx;" scroll-x="true" :scroll-with-animation="true" :enable-flex="true">
					<view class="tab-container">
						<view class="tab-item" v-for="(item, index) in categoryList" @click="handleTabsChange(item)" :class="filterData.activityCategoryId === item.id ? 'active' : ''" :key="item.id">
							<image v-if="item.iconPic" :src="item.iconPic"></image>
							<text class="tab-item-text">{{item.nameForMerchant}}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view style="padding: 30rpx 24rpx;background-color: #fff;z-index: 9999;">
				<swiper class="swiper" circular :indicator-dots="false" :autoplay="false" :interval="5000">
					<swiper-item v-for="(item, index) in swiperList" :key="item.id" @click="handleSwiperClick(index)">
						<image class="swiper-item" :src="item.bannerPic" mode="aspectFill" />
					</swiper-item>
				</swiper>
				<scroll-view style="display: flex;height: 80rpx;position: relative;" scroll-x="true" :scroll-with-animation="true" :enable-flex="true">
					<view class="filter-item" @click="handleSort">
						<text :style="{color: dropShow ? '#ffb803' : '#333'}">{{ sortData.find(item => item.value === filterData.sortType)?.name }}</text>
						<tui-icon class="tui-top-icon" name="turningdown" :size="14" :color="dropShow ? '#ffb803' : '#333'" :bold="true"></tui-icon>
					</view>
					<view class="filter-item" @click="openCity">
						<text>{{this.filterData.cityName}}</text>
						<tui-icon class="tui-top-icon" name="turningdown" :size="14" color="#333" :bold="true"></tui-icon>
					</view>
				</scroll-view>
			</view>
			<view class="tui-sort-dropdown" v-if="dropShow">
				<view class="tui-drop-item" :class="[filterData.sortType === item.value ?'active':'']" v-for="(item,index) in sortData" :key="index"
				 @click="handleSortClick" :data-index="index">
					<text class="tui-ml tui-middle">{{item.name}}</text>
				</view>
			</view>
		</view>
		<view class="tui-sort-mask" v-if="dropShow" @click="handleSortClose"></view>
		<!-- 列表 -->
		<view class="active-list">
			<view class="empty" v-if="storeList.length === 0">
				<image class="empty-img" src="https://static.wddzq.com/static/kong.png"></image>
				<view class="empty-text">暂无数据～</view>
			</view>
			
			<view class="active-item" v-for="item in storeList" :key="item.id" @click="handleApply(item.id)">
				<image v-if="item.recommendType === 1" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%" src="https://static.wddzq.com/static/kuang.png" />
				<image class="active-item-image" mode="aspectFill" :src="item.logoUrl" />
				<view class="active-content">
					<view class="active-header">
						<view class="active-header-title">{{item.name}}</view>
						<image v-if="item.recommendType === 1" src="https://static.wddzq.com/static/jin.png" />
						<image v-if="item.recommendType === 2" src="https://static.wddzq.com/static/yin.png" />
					</view>
					<view class="active-date">{{item.workTime}}</view>
					<view class="active-addr">
						<text class="active-addr-text">{{item.address}}</text>
						<text class="active-addr-ju">{{item.distanceShow}}</text>
					</view>
					<view class="active-desc">{{item.intro}}</view>

          <view v-if="item.merchantProductVO" class="active-bottom-wrapper" @click.stop="()=>navigateToPack(item.merchantProductVO.id)">

            <view class="price-wrapper">
              <image class="price-icon" src="/static/store/discount-icon.png"/>
              <view class="price-right-wrapper">
                <text class="price-unit">¥</text>
                <text class="price">{{item.merchantProductVO.price}}</text>
              </view>
            </view>

            <view class="original-price-wrapper">
              <text class="original-price-tag">补贴价</text>
              <text class="original-price">¥{{item.merchantProductVO.originalPrice}}</text>
            </view>

            <text class="price-desc">点击查看详情</text>

          </view>
				</view>
			</view>
		</view>
		
		<!-- 城市弹窗 -->
		<u-popup :show="showCity" closeOnClickOverlay :customStyle="{ height: ((systemInfo?.screenHeight || 300) - 200) + 'px' }" mode="bottom" :round="18" @close="closeCity" @open="openCity" :zIndex="1000000">
				<view style="border-top-left-radius: 18rpx;border-top-right-radius: 18rpx;overflow: hidden;">
					<view style="height: 40px;display: flex;align-items: center;justify-content: center;">
						<text style="font-size: 28rpx;color: #333;">选择城市</text>
					</view>
					<view class="u-index-list" style="padding: 0 112rpx 0 24rpx;position: relative;">
						<view style="position: absolute;right: 18rpx;top: 20rpx;z-index: 500;padding: 10rpx 0;background-color: #f2f2f2;width: 34rpx;border-radius: 17rpx;">
							<view style="font-size: 20rpx;color: #333;text-align: center;margin-bottom: 10rpx;" v-for="item in cityList">{{item.letter}}</view>
						</view>
						<view style="height: 80rpx;background-color: #f2f2f2;border-radius: 20px;padding: 0 30rpx;">
							<u--input border="none" customStyle="height: 80rpx;" fontSize="24" placeholder="搜索城市" :value="searchValue" @input="handleSearchCityChange"></u--input>
						</view>
						<scroll-view
							:offset-accuracy="1"
							:style="{
								height: ((systemInfo?.screenHeight || 300) - 200) + 'px'
							}"
							scroll-y
							@scroll="scrollHandler"
							ref="uList"
						>
							<template>
								<view v-for="(item, index) in cityListSearch" :key="index">
									<view style="font-weight: bold;font-size: 28rpx;color: #333;padding: 24rpx 0;border-bottom: 1rpx solid #DDDDDD;">{{ item.letter }}</view>
									<!-- <u-index-anchor :text="cityList[index]" :height="80" bgColor="#fff" size="36"></u-index-anchor> -->
									<view class="list-cell" v-for="(cell, i) in item.data" :data-item="cell" @click="handleCitySelect">
										{{cell.cityName || '-'}}
									</view>
								</view>
							</template>
						</scroll-view>
					</view>
				</view>
		</u-popup>
		
		<tui-ctabbar :current="1"></tui-ctabbar>
	</view>
</template>

<script>
	import { getMerchantPage, getActivityCategoryList, getBannerList, getCityViewVoList } from '../../config/api.js';
	import { to, getSystemInfo } from '../../config/utils.js';
	export default {
		data() {
			return {
				systemInfo: '',
				swiperList: [],
				// 城市弹窗
				showCity: false,
				dropShow: false,
				initNavigation: {
					opacity: 1
				},
				categoryList: [
					{
						id: null,
            nameForMerchant: '全部'
					}
				],
				loading: false,
				hasMore: true,
				filterData: {
					pages: 1,
					size: 20,
					activityCategoryId: null,
					activityType: '1',
					cityCode: 350200,
					cityName: '厦门市',
					sortType: 1,
				},
				sortData: [
					{
						name: '智能排序',
						value: 1
					},
					{
						name: '距离由近到远',
						value: 2
					},
				],
				storeList: [],
				// 城市数据
				cityList: [],
				cityListSearch: [],
			}
		},
		onReady() {
			this.systemInfo = getSystemInfo();
			
			this.fetchBanner();
			this.fetchActivityCategoryList();
			this.fetchCityViewVoList();
			
			let localCity = uni.getStorageSync('__local__city');
			// 如果本地有存就用本地存的
			if(localCity) {
				let citys = localCity.split(',');
				this.filterData = {
					...this.filterData,
					cityCode: citys[0],
					cityName: citys[1]
				};
			}
			this.resetStoreList();
		},
		onPullDownRefresh() {
			// if(!this.hasMore) return;
			this.fetchBanner();
			this.fetchActivityCategoryList();
			this.resetStoreList();
		},
		onReachBottom() {
		
			if(this.loading || !this.hasMore) return;
			this.filterData = {
				...this.filterData,
				pages: this.filterData.pages + 1
			};
			this.fetchStoreNormalPage(this.filterData);
		},
		methods: {
      navigateToPack(productId){
        uni.navigateTo({
          url: `/pages/pack/pack?productId=${productId}`
        })
      },
			closeCity() {
				this.showCity = false;
			},
			openCity() {
				this.showCity = true;
			},
			handleSearchCityChange(value) {
				this.searchValue = value;
			
				let cityListSearch = this.cityList.map(item => {
					let { data, letter } = item;
					let _data = (data || []).filter(it => it.cityName.indexOf(this.searchValue) > -1) || [];
			
					return {
						letter,
						data: _data
					};
				})
				this.cityListSearch = cityListSearch.filter(item => item.data.length > 0);
			},
			// 排序点击事件
			handleSort() {
				this.dropShow = !this.dropShow;
				if(this.dropShow) {
					this.showCity = false;
				}
				// if(this.dropShow) {
				// 	uni.pageScrollTo({
				// 		scrollTop: this.stickyTop + pxToRpx(12)
				// 	})
				// }
			},
			handleSortClose() {
				this.dropShow = false;
			},
			handleSortClick(e) {
				const { currentTarget } = e || {};
				const { dataset } = currentTarget || {};
				this.filterData = {
					...this.filterData,
					sortType: this.sortData[dataset.index].value
				};
				this.handleSortClose();
				this.resetStoreList();
			},
			
			handleTabsChange(data) {
				const { id } = data || {};
				this.filterData = {
					...this.filterData,
					activityCategoryId: id
				};
				this.resetStoreList();
			},
			handleSwiperClick(index) {
				let current = this.swiperList[index];
				if(!current) return;
				if(current.actionType === 1) {
					current.actionUrl && uni.navigateTo({
						url: current.actionUrl
					})
				} else if(current.actionType === 2) {
					current.actionUrl && uni.navigateTo({
						url: `/pages/webview/webview?url=` + encodeURIComponent(`${current.actionUrl}`)
					})
				}
			},
			
			handleApply(storeId) {
				uni.navigateTo({
					url: `/pages/shop-detail/shop-detail?storeId=${storeId}`
				})
			},
			handleCitySelect(e) {
				const { cityCode, cityName } = e.currentTarget?.dataset?.item || {};
				this.filterData = {
					...this.filterData,
					cityCode,
					cityName,
				};
				this.showCity = false;
				this.resetStoreList();
				uni.setStorage({
					key: '__local__city',
					data: cityCode + ',' + cityName
				})
			},
			async fetchBanner() {
				const [err, banner] = await to(getBannerList({ position: '3' }));
				if(err) return;
				this.swiperList = banner?.data || [];
			},
			// 重新请求接口
			resetStoreList() {
				let params = {
					...this.filterData,
					pages: 1,
				};
				this.loading = false;
				this.hasMore = true;
				// this.activityList = [];
				this.fetchStoreNormalPage(params, true);
			},
			async fetchActivityCategoryList() {
				const [err, activityCategory] = await to(getActivityCategoryList());
				if(err) return;
				this.categoryList = [
					...this.categoryList,
					...(activityCategory?.data || [])
				];
			},
			
			async fetchStoreNormalPage(params, isClear) {
				this.loading = true;
				params.current = params.pages;
				const [err, activityListData] = await to(getMerchantPage(params));
				this.loading = false;
				uni.stopPullDownRefresh();
				if(err) return;
				let records = activityListData?.data?.records || [];
			
				if(records.length <= 0) {
					this.hasMore = false;
				}
				this.storeList = isClear ? records: this.storeList.concat(records);
			},
			async fetchCityViewVoList() {
				const [err, cityData] = await to(getCityViewVoList());
				if(err) return;
				// let cityList = [], cityArr = [];
				// (cityData?.data || []).forEach(city => {
				// 	cityList.push(city.cityFirstLetter || '-');
				// 	cityArr.push(city.cityVoList || []);
				// })
				// this.cityList = cityList;
				// this.cityArr = cityArr;
				let cityList = [];
				(cityData?.data || []).forEach(city => {
					let data = city.cityVoList || []; //?.map(item => ({ id: item.cityCode, name: item.cityName })) || []
					cityList.push({
						letter: city.cityFirstLetter || '-',
						data: data
					})
				})
				this.cityList = cityList;
				this.cityListSearch = cityList;
			},
		}
	}
</script>

<style>
	.tui-header-icon {
		width: 203rpx;
		height: 36rpx;
		position: fixed;
		top: 0;
		left: 20rpx;
		padding: 0 12rpx;
		display: flex;
		align-items: center;
		transform: translateZ(0);
		z-index: 99999;
		box-sizing: border-box;
		animation: fade-in .5s ease;
	}
	
	@keyframes fade-in {
	  from {
	    opacity: 0;
	  }
	  to {
	    opacity: 1;
	  }
	}
	
	.header-container {
		background-color: #fff;
		/* border-top-left-radius: 18rpx; */
		/* border-top-right-radius: 18rpx; */
		position: relative;
		z-index: 100;
		/* padding: 24rpx 0; */
		padding-top: 20rpx;
	
	}
	.tab-container {
		display: flex;
		position: relative;
		z-index: 1000;
	}
	.tab-item {
		/* width: 200rpx; */
		width: 150rpx;
		/* padding: 0 20rpx; */
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}
	.tab-item.active::after {
		position: absolute;
		content: ' ';
		left: 37rpx;
		bottom: 20rpx;
		width: 76rpx;
		height: 12rpx;
		background-color: #FFB803;
		z-index: 99;
		border-radius: 3rpx;
	}
	.tab-item image {
		width: 44rpx;
		height: 44rpx;
		margin-right: 4rpx;
		position: relative;
		z-index: 100;
	}
	.tab-item .tab-item-text {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		position: relative;
		z-index: 100;
	}

	.swiper {
		height: 140rpx;
		border-radius: 18rpx;
		overflow: hidden;
	}
	.swiper-item {
		display: block;
		width: 100%;
		height: 140rpx;
		line-height: 140rpx;
		text-align: center;
		background-color: aquamarine;
	}
	
	.filter-item {
		padding: 0rpx 20rpx 0 30rpx;
		background-color: #f2f2f2;
		border-radius: 60rpx;
		display: flex;
		align-items: center;
		margin-right: 8rpx;
		margin-top: 20rpx;
	}
	
	.filter-item text {
		font-size: 26rpx;
		color: #333;
		padding-right: 6rpx;
	}
	.tui-top-icon {
		padding-top: -4rpx;
	}


	.active-list {}
	.active-item {
		background-color: #fff;
		padding: 24rpx;
		border-radius: 18rpx;
		display: flex;
		margin: 16rpx 24rpx 0 24rpx;
		position: relative;
	}
	.active-item .active-item-image {
		width: 176rpx;
		height: 176rpx;
		border-radius: 18rpx;
		position: absolute;
		background-color: #f2f2f2;
	}
	.active-content {
		flex: 1;
		margin-left: 192rpx;
		width:477rpx;
	}
	.active-header {
		display: flex;
		align-items: center;
	}
	.active-header .active-header-title {
		flex: 1;
		font-size: 30rpx;
		font-weight: bold;
		color: #333333;
		height: 42rpx;
		line-height: 42rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	.active-header image {
		width: 32rpx;
		height: 28rpx;
	}
	.active-date {
		height: 32rpx;
		font-size: 24rpx;
		font-weight: 400;
		color: #666666;
		line-height: 32rpx;
		margin: 16rpx 0;
	}
	.active-addr {
		display: flex;
		align-items: center;
		height: 32rpx;
		line-height: 32rpx;
	}
	.active-addr .active-addr-text {
		display: inline-block;
		flex: 1;
		font-size: 24rpx;
		font-weight: 400;
		color: #999999;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	.active-addr .active-addr-ju {
		font-size: 24rpx;
		color: #333333;
	}
	.active-desc {
		height: 32rpx;
		font-size: 24rpx;
		font-weight: 400;
		color: #333333;
		line-height: 32rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		margin-top: 16rpx;
    margin-bottom: 16rpx;
	}
  .active-bottom-wrapper{
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1rpx solid #EEEEEE;
    padding-top: 16rpx;
  }
  .price-wrapper{
    display: flex;
    align-items: center;
  }
  .price-right-wrapper{
    display: flex;
    align-items: baseline;
  }
  .price-icon{
    width: 32rpx;
    height: 32rpx;
    margin-right: 8rpx;
  }
  .price-unit{
    font-size: 22rpx;
    font-weight: 600;
    color: #FF8F1F;
  }
  .price{
    font-size: 30rpx;
    font-weight: 600;
    color: #FF8F1F;
  }

  .original-price-wrapper{
    display: flex;
    align-items: center;
  }

  .original-price-tag{
    line-height: 34rpx;
    padding: 0 8rpx;
    background: rgba(255,143,31,0.1);
    border-radius: 8rpx;
    border: 1rpx solid rgba(255,143,31,0.3);
    font-size: 20rpx;
    font-weight: 500;
    color: #FF8F1F;
    margin-right: 8rpx;
  }
  .original-price{
    font-size: 24rpx;
    font-weight: 400;
    color: #AAAAAA;
	text-decoration: line-through;
  }
  .price-desc{
    font-size: 24rpx;
    font-weight: 400;
    color: #333333;
  }


	/* 城市列表 */
	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;
	}
	/* 城市列表 */
	
	
	.tui-sort-dropdown {
		position: absolute;
		bottom: -158rpx;
		left: 0;
		z-index: 10000;
		width: 100%;
		background-color: #fff;
		border-bottom-left-radius: 18rpx;
		border-bottom-right-radius: 18rpx;
		animation: fade-in .3s ease;
		animation: fade-Y .3s ease;
	}
	@keyframes fade-in {
	  from {
	    opacity: 0;
	  }
	  to {
	    opacity: 1;
	  }
	}
	
	@keyframes fade-Y {
	  from {
			bottom: 0rpx;
	  }
	  to {
			bottom: -158rpx;
	  }
	}
	
	.tui-sort-mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, .5);
		z-index: 9998;
	}
	
	.tui-top-item {
		height: 26rpx;
		line-height: 26rpx;
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.tui-top-item .tui-bold.active {
		color: #ffb803;
	}
	.tui-top-icon {
		/* padding-top: 10rpx; */
	}
	
	/* 智能排序下拉样式 */
	.tui-scroll-box {
		background-color: #fff;
	}
	
	.tui-drop-item {
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #000;
	}
	.tui-drop-item.active {
		color: #ffb803;
	}
	
</style>
